#coding: utf-8

import os, sys
#print os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.split(os.path.abspath(os.path.dirname(__file__)))[0]) 
#print sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from meal.models import Restaurant, Course, Order
from django.contrib.auth.models import User
from meal.meal_sim import *
from similar.sim import *
from django.conf import settings

from django.core.mail import send_mail as django_send_mail
import threading
from datetime import datetime as dt

def send_mail(subject, message, from_email, recipient_list,fail_silently=False, auth_user=None, auth_password=None):
 
    class Sender(threading.Thread): 
        def run(self):
            django_send_mail(subject, message, from_email, recipient_list, fail_silently, auth_user, auth_password)
 
    s=Sender()
    s.start()
    return True

from django.core.mail import EmailMessage
from django.template import loader

def send_html_mail(subject, html_content, recipient_list):
    msg = EmailMessage(subject, html_content, settings.EMAIL_HOST_USER, recipient_list)
    msg.content_subtype = "html" # Main content is now text/html
    msg.send()
    print subject, html_content, settings.EMAIL_HOST_USER, recipient_list

#subject = u'邮件主题'
#html_content = loader.render_to_string(template_path, {})
#send_html_mail(subject, html_content, [])

if __name__ == '__main__':
    
    #django_send_mail('test', 'test', 'jiantao@staff.sina.com.cn', ['jiantao@staff.sina.com.cn'], True, None, None)
    #print Restaurant.objects.all()
    
    prefs_cnt,user_set,order_prefs = init_order_prefs()
    
    #similarity = sim_pearson
    similarity = sim_distance
    
    order_taste_sim = {}
    for user1 in user_set:
        for user2 in user_set:
            order_taste_sim.setdefault(user1, {})            
            order_taste_sim[user1][user2] = similarity(order_prefs, user1, user2)
    
    print order_taste_sim
    print user_set
    for user in user_set:    
        itemsim = calculateSimilarItems(order_prefs, 5, similarity)    
        top_matches = topMatches(order_prefs, user, 5, similarity)
        print top_matches
        
        recommendations = getRecommendations(order_prefs, user, similarity)
        print recommendations    
        
        item_recommds = getRecommendedItems(order_prefs, itemsim, user)
        print item_recommds
        
        subject = u'今日推荐'
        html_content = loader.render_to_string('order_prefs.html',
                          {'prefs_cnt':prefs_cnt,
                           'order_taste_sim':order_taste_sim,
                           'user_set':user_set,
                           'top_matches':top_matches,
                           'recommendations':recommendations,
                           'item_recommds':item_recommds})
        print html_content
        send_html_mail(subject, html_content, [user.email])
        